package com.zingto.android.chenapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    public static CH34xUARTDriver driver;
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
    private Button open_btn;
    private Button send_btn;
    private TextView angle_text;
    private boolean isOpen=false;
    public int baudRate;
    public byte stopBit;
    public byte dataBit;
    public byte parity;
    public byte flowControl;
    private SensorManager mSensorManager;
    private final float[] mAccelerometerReading = new float[3];
    private final float[] mMagnetometerReading = new float[3];
    private final float[] mRotationMatrix = new float[9];
    private final float[] mOrientationAngles = new float[3];
    private EasyPickerView easyPickerView;
    private ProgressBar progressbarpitch;
    private ProgressBar progressbarroll;
    private int angle_pitch=0;
    private int angle_roll=0;
    private TextView pitch_text;
    private TextView roll_text;
    private byte[] to_send = {(byte) 0xEE,0x02,0x00,0x00,0x00,0x00,0x00,0x00};
    private boolean isfollow=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        if (!driver.UsbFeatureSupported())//判断系统是否支持OTG
        {
            Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("提示")
                    .setMessage("您的手机不支持OTG，请更换其他手机再试！")
                    .setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
                SensorManager.SENSOR_DELAY_NORMAL);
        initUI();
    }
    private void initUI(){
        open_btn=(Button)findViewById(R.id.open_btn);
        open_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openUART();
            }
        });
        send_btn=(Button)findViewById(R.id.send_btn);
        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isfollow=true;
                /*byte[] to_send = {0x01,0x02,0x03};
                int retval = driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
                if (retval < 0)
                    Toast.makeText(MainActivity.this, "发送失败!",
                            Toast.LENGTH_SHORT).show();*/
            }
        });
        angle_text=(TextView)findViewById(R.id.angle_text);
        easyPickerView = (EasyPickerView)findViewById(R.id.epv_m);
        final ArrayList<String> dataList = new ArrayList<>();
        for (int i = 0; i < 360; i++)
            dataList.add("" + i);
        easyPickerView.setDataList(dataList);
        easyPickerView.moveTo(91);
        easyPickerView.setOnScrollChangedListener(new EasyPickerView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int curIndex) {
                to_send[2]= (byte) (curIndex);
                to_send[3]= (byte) (90);
                driver.WriteData(to_send, to_send.length);
            }
            @Override
            public void onScrollFinished(int curIndex) {
                to_send[2]= (byte) (curIndex);
                to_send[3]= (byte) (90);
                driver.WriteData(to_send, to_send.length);
            }
        });
        progressbarpitch = (ProgressBar) findViewById(R.id.progressbarpitch);
        progressbarpitch.setProgress(90);
        progressbarroll = (ProgressBar) findViewById(R.id.progressbarroll);
        progressbarroll.setProgress(90);
        pitch_text=(TextView)findViewById(R.id.pitch_text);
        roll_text=(TextView)findViewById(R.id.roll_text);
    }
    private void openUART(){
        if (!isOpen) {
            int retval = driver.ResumeUsbList();
            if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
            {
                Toast.makeText(MainActivity.this, "打开设备失败!",
                        Toast.LENGTH_SHORT).show();
                driver.CloseDevice();
            } else if (retval == 0){
                if (!driver.UartInit()) {//对串口设备进行初始化操作
                    Toast.makeText(MainActivity.this, "设备初始化失败!",
                            Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, "打开设备失败!",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(MainActivity.this, "打开设备成功!",
                        Toast.LENGTH_SHORT).show();
                isOpen = true;
                new readThread().start();//开启读线程读取串口接收的数据
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                baudRate=115200;
                if (driver.SetConfig(baudRate, dataBit, stopBit, parity,//配置串口波特率，函数说明可参照编程手册
                        flowControl)) {
                    Toast.makeText(MainActivity.this, "串口设置成功!",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "串口设置失败!",
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MainActivity.this, "设备未授权!",
                        Toast.LENGTH_SHORT).show();
            }
        } else {
            isOpen = false;
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            driver.CloseDevice();
            Toast.makeText(MainActivity.this, "关闭设备!",
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            System.arraycopy(sensorEvent.values, 0, mAccelerometerReading,
                    0, mAccelerometerReading.length);
        }
        else if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            System.arraycopy(sensorEvent.values, 0, mMagnetometerReading,
                    0, mMagnetometerReading.length);
        }
        updateOrientationAngles();
    }
    public void updateOrientationAngles() {
        mSensorManager.getRotationMatrix(mRotationMatrix, null, mAccelerometerReading, mMagnetometerReading);
        mSensorManager.getOrientation(mRotationMatrix, mOrientationAngles);
        if (isfollow) {
            to_send[3] = (byte) (mOrientationAngles[1] * 180 / Math.PI+90);
            to_send[2] = (byte) (mOrientationAngles[2] * 180 / Math.PI+90);
            driver.WriteData(to_send, to_send.length);
            //angle_text.setText("PITCH " + mOrientationAngles[1] * 180 / Math.PI + " \nROLL " + mOrientationAngles[2] * 180 / Math.PI);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    private class readThread extends Thread {

        public void run() {

            final byte[] buffer = new byte[4096];

            while (true) {

                if (!isOpen) {
                    break;
                }
                int length = driver.ReadData(buffer, 4096);
                int byte0=(buffer[0]<0)?(256+buffer[0]):buffer[0];
                int byte1=(buffer[1]<0)?(256+buffer[1]):buffer[1];
                int byte2=(buffer[2]<0)?(256+buffer[2]):buffer[2];
                int byte3=(buffer[3]<0)?(256+buffer[3]):buffer[3];
                if (length == 4 && byte0 == 0xEE && byte1 == 0x01) {
                    angle_pitch=byte2;
                    angle_roll=byte3;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pitch_text.setText(""+angle_pitch);
                            roll_text.setText(""+angle_roll);
                            progressbarpitch.setProgress(angle_pitch);
                            progressbarroll.setProgress(angle_roll);
                        }
                    });
                }
            }
        }
    }
}
